package org.rbi.net;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.rbi.context.TransmitterContext;
import org.rbi.exceptions.TypeNotSupportedException;

import java.net.InetSocketAddress;

public class TCPRemoteConnector extends AbstractConnector {
    @Override
    public void connect(TransmitterContext context) throws TypeNotSupportedException, InterruptedException {
        if (!(context instanceof IPAccessible) || !(context instanceof PortAccessible)) {
            throw new TypeNotSupportedException("该类型不被支持使用该连接器");
        }
        String IP = ((IPAccessible) context).getIP();
        Integer port = ((PortAccessible) context).getPort();
        connect0(IP,port);
    }

    private void connect0(String IP,Integer port) throws InterruptedException {
        Bootstrap handler = new Bootstrap()
                .group(
                        new NioEventLoopGroup()
                )
                .channel(NioSocketChannel.class)
                .handler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                            }
                        }
                );
        ChannelFuture future = handler.connect(IP,port).sync();

    }
}
